<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域加布局容器 -->
    <el-card>
      <el-button type="primary">添加角色</el-button>
      <!-- 角色表格 -->
      <el-table :data="rolesData" border stripe
      style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="[i === 0 ? 'tagtop' : '', 'tagbtm', 'venter', 'elrow']" v-for="(item,i) in scope.row.children"
            :key="item.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeTag(scope.row, item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '' : 'tagtop', 'venter']"
                v-for="(item2, i2) in item.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable
                    @close="removeTag(scope.row, item2.id)">
                      {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children"
                    :key="item3.id" closable
                    @close="removeTag(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <!-- 操作按钮 -->
        <el-table-column prop="date" label="操作">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <!-- 分配权限 -->
            <el-button type="warning" icon="el-icon-setting"
            size="mini" @click="setRoles(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setDialogVisible"
      width="50%"
      @closed="restList">
      <!-- 树形控件 -->
      <el-tree :data="rolesTreeData" :props="setprops" show-checkbox node-key="id"
      default-expand-all :default-checked-keys="defKeys" ref="treeRef">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updataRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 页面首次渲染获取到的表格数据
      rolesData: [],
      // 分配权限树形数据
      rolesTreeData: [],
      // 控制分配权限对话框的显示与隐藏
      setDialogVisible: false,
      // 树形控件配置属性绑定对象
      setprops: {
        label: 'authName',
        children: 'children'
      },
      // 默认勾选的三级节点id数组
      defKeys: [],
      // 角色的id
      roleId: ''
    }
  },
  created() {
    this.getRolesData()
  },
  methods: {
    // 首次渲染页面获取数据
    async getRolesData() {
      const { data: res } = await this.$http.get('roles')
      this.rolesData = res.data
    },
    // 监听权限标签删除事件
    async removeTag(role, rightId) {
      const result = await this.$confirm('此操作将永久删除该权限, 是否继续?', '删除权限', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 确认删除返回值是confirm
      if (result !== 'confirm') return
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.info('已取消删除')
      // 更新当前的children权限数据
      role.children = res.data
    },
    // 监听分配权限按钮事件
    async setRoles(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rolesTreeData = res.data
      this.getArr(role, this.defKeys)
      this.setDialogVisible = true
    },
    getArr(node, arr) {
      // 控制三级权限，当三级权限全被选中二级权限自然被选中，一级权限类似
      // 如果没有children证明是第三级节点直接将节点的id push到数组中
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        return this.getArr(item, arr)
      })
    },
    // 监听对话框的关闭事件
    restList() {
      this.defKeys = []
    },
    // 点击分配权限对话框确定按钮更新权限
    async updataRoles() {
      // 获取所有半选中和全选中的id数组
      const halfArr = [
        ...this.$refs.treeRef.getHalfCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys()
      ]
      const rights = halfArr.join(',')
      console.log(halfArr)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: rights })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.setDialogVisible = false
      this.getRolesData()
      this.$message.success('更新成功')
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.elrow {
  margin-left: 50px;
}
.tagbtm {
  border-bottom: 1px solid #eee
}
.tagtop {
  border-top: 1px solid #eee
}
.venter {
  display: flex;
  align-items: center;
}
</style>
